import { Component, NgZone, ChangeDetectorRef, ChangeDetectionStrategy, ElementRef, Input } from '@angular/core';
import { _HttpClient, DatePipe } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
import { format } from 'date-fns';

/**
 * 实销饼图
 */
@Component({
  selector: 'app-actualsale-pie',
  templateUrl: './prod-actual-pie.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.card]': 'true',
  },
})
export class ProdActualPieComponent {
  @Input()
  loading = true;
  @Input()
  data = [];
  @Input()
  time = null;
  @Input()
  title = '';
  @Input()
  type = '';

  _start = '';
  _end = '';

  @Input()
  set start(val) {
    if (val) {    
      this._start = format(val, 'YYYY-MM-DD');
    }
  }

  @Input()
  set end(val) {
    if (val) {      
      this._end = format(val, 'YYYY-MM-DD');
    }
  }

  private chart: any;

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  render(er: ElementRef) {
    this.ngZone.runOutsideAngular(() => setTimeout(() => this.init(this.type, er.nativeElement), 50));
  }

  private init(type, container: HTMLElement) {
    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true,
      height: 160,
      padding: 0,
    }));
    chart.tooltip(false);
    chart.legend(false);
    chart.coord('theta', {
      radius: 0.75,
    });

    chart
      .intervalStack()
      .position(`${type === 's' ? 'count' : 'count2'}`)
      .color('text', ['#45a3fc', '#f0657d', '#fad352'])
      .opacity(1)
      .label('percent', {
        textStyle: {
          fill: '#666',
        },
        formatter: (val: any, item: any) =>
          `${item.point.text}: ${type === 's' ? item.point.count : item.point.count2} `,
      });

    chart.render();

    this.ngZone.runOutsideAngular(() => {
      const ds = new DataSet();
      const dv = ds.createView().source(
        this.data.map(r => {
          if (+r.count < 0) {
            r.count = 0;
          }
          if (+r.count2 < 0) {
            r.count2 = 0;
          }
          return r;
        }),
      );
      dv.transform({
        type: 'percent',
        field: `${type === 's' ? 'count' : 'count2'}`,
        dimension: 'text',
        as: 'percent',
      });
      chart.changeData(dv);
    });
  }
}
